import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import utils from 'src/common/utils';
import DataBase from 'src/config/database';
import { video_SubAppId_List } from 'src/setting';
import { Like, Repository,Not, InsertResult } from 'typeorm';
import { InternetCelebrity } from '../internetCelebrity/internetCelebrity.entity';
import { InternetCelebrityGroup } from '../internetCelebrityGroup/internetCelebrityGroup.entity';
import { EnumInternetCelebrityGroupIsInitEnum, EnumInternetCelebrityGroupTypeEnum } from '../internetCelebrityGroup/internetCelebrityGroup.enum';
import { UserSetting } from '../userSetting/userSetting.entity';
import { OverseasEnum } from '../video/video.enum';
import { Platform } from './platform.entity';
import { TypeEnum } from './platform.enum';
import { EnumInternetCelebrityOverseasEnum } from '../internetCelebrity/internetCelebrity.enum';
import { InternetCelebrityGroupCheck } from '../internetCelebrityGroupCheck/internetCelebrityGroupCheck.entity';
import { RedisCacheService } from '../redisCache/redisCache.service';

@Injectable()
export class PlatformService {
  constructor(
    @InjectRepository(Platform)
    private respository: Repository<Platform>,
    @InjectRepository(UserSetting)
    private userSettingRespository: Repository<UserSetting>,
    @InjectRepository(InternetCelebrityGroup)
    private internetCelebrityGroupRespository: Repository<InternetCelebrityGroup>,
    @InjectRepository(InternetCelebrity)
    private icRepository: Repository<InternetCelebrity>,
    @InjectRepository(InternetCelebrityGroupCheck)
    private internetCelebrityGroupCheckRepository: Repository<InternetCelebrityGroupCheck>,
    private readonly redisCacheService: RedisCacheService,
  ) {}

  findAll(): Promise<Platform[]> {
    return this.respository.find();
  }


  /**
   * 查询用户在微信端回答的平台信息
   * @returns 
   */
  async findWXForentUserAnswer_By_Wx_User(wx_user: string): Promise<any>{
    return await this.respository.query(`
      select a.id as id_platform,a.platform,a.wx_user,b.id as id_ic,b.name as ic_name,b.img,b.img_id,b.avatar_img,b.avatar_id,b.account from platform a
      inner join internet_celebrity b on b.platform = a.id and b.wx_user = a.wx_user
      where a.wx_user = ? and a.type = 1
      order by a.id asc
    `,[wx_user])
  }

  /**
   * 查询网红下的所有平台
   * @param ic_group 
   * @returns 
   */
  findAll_By_Ic_Group(ic_group: number): Promise<Platform[]> {
    return this.respository.query(`
      select a.id as id_platform,a.platform,a.wx_user,b.id as id_ic,b.name as ic_name,b.img,b.img_id,b.avatar_img,b.avatar_id,b.account from platform a
      inner join internet_celebrity b on b.platform = a.id and b.wx_user = a.wx_user
      where a.ic_group = ?
      order by a.id asc
    `,[ic_group])
  }

  getIDCard(){
    let id = ''
    let loop = async () => {
      id = utils.randomNumberID(7)
      if(await this.internetCelebrityGroupRespository.findOne({where:{id_card: id}})){
        loop()
      }
    }
    loop()
    return id
  }

  async insertIcCheck(ic_group, wx_user, list){
    let findIc = await this.internetCelebrityGroupRespository.findOne({where:{wx_user: wx_user, type: EnumInternetCelebrityGroupTypeEnum.overseas}})
    if(findIc){
      ic_group = findIc.id
    }
    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    try {
      let itcList = []
      let newList = list.filter(e => e.platform.platform)
      if(newList.length > 0){
        list = newList
      }
      list.map((e: any) => {
        let item = new InternetCelebrityGroupCheck()
        item.platform = e.platform.platform
        item.account = e.ic.account
        item.name = e.ic.name
        item.avatar_img = e.ic.avatar_img
        item.avatar_img_id = e.ic.avatar_id
        item.create_time = new Date()
        item.wx_user = wx_user
        item.ic_group = ic_group
        itcList.push(item)
      })
      await this.internetCelebrityGroupCheckRepository.createQueryBuilder(null, queryRunner)
        .delete()
        .where({wx_user:wx_user})
        .execute()

      await this.internetCelebrityGroupCheckRepository.createQueryBuilder(null, queryRunner)
        .insert()
        .into(InternetCelebrityGroupCheck)
        .values(itcList)
        .execute()
      
      await queryRunner.commitTransaction()
      await queryRunner.release();
      return {ic_group: ic_group, error: ''}
    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return {error:err}
    }
   
  }

  async deletIcCheck(wx_user: string, ic_group?: number){
    let result = await this.internetCelebrityGroupCheckRepository.delete({wx_user: wx_user})
    if(result.affected > 0){
      return {ic_group: ic_group, error: ''}
    }else{
      return {error: '撤回失败。'}
    }
  }

  /**
   * 添加平台
   * @param platformList
   * @param wx_user
   */
  async addPlatform(platformList:{platform:Platform,ic:InternetCelebrity}[], wx_user: string, ic_group?: number){
    //查询是否有审核中的平台信息
    let checkPlatformCount = await this.internetCelebrityGroupCheckRepository.find({where:{wx_user: wx_user}})
    if(checkPlatformCount.length > 0){
      return await this.deletIcCheck(wx_user, ic_group)
    }
    //查询是否有认证的一类视频，如果有，跳转到提交审核
    let level1Count = await this.respository.query(`
      select count(1) as sumCount
      from video
      where video.original = 1 and video.overseas = 1 and video.profit_type = 0 and wx_user = ? and source = 0
    `,[wx_user])
    if(Number(level1Count[0].sumCount) > 0){
      return await this.insertIcCheck(ic_group, wx_user, platformList)
    }


    //查询是否打开了海外素材作者
    let isOverseas = true
    let platformId, icId
    //查找认证过后的ic_group
    let findIcGroup = await this.internetCelebrityGroupRespository.findOne({where:{wx_user: wx_user, type: EnumInternetCelebrityGroupTypeEnum.overseas}})
    if(findIcGroup){
      ic_group = findIcGroup.id
    }

    //认证用户，如果是清空网红信息
    let findUserInfo = await this.userSettingRespository.findOne({where:{wx_user: wx_user, key: 'overseas', value: "1"}})
    if(findUserInfo && !platformList.find(e => e.platform.platform)){
      //查询当前用户是否有1类视频已经产生盈利了，如果产生，需要先删除所有已经盈利的视频
      let findIsProfit = await this.respository.query(`
        select * 
        from profit
        inner join answer on answer.id = profit.answer_id
        inner join video on video.id = answer.video_id
        where video.profit_type = 0 and video.original = 1 and video.overseas = 1 and profit.status != 4 and video.wx_user = ?
      `, [wx_user])
      if(findIsProfit.length > 0){
        return {error:`必须先删除所有有盈利的Ⅰ类视频才能清空社交平台信息`}
      }
    }

    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    try {
      let len = platformList.length
      let platformCount = isOverseas ? 3 : 1
      for(let i = 0 ; i < platformCount - len; i++){
        let addpf = new Platform()
        let addic = new InternetCelebrity()
        platformList.push({platform:addpf,ic:addic})
      }
      len = platformList.length
      let run = () => {
        return new Promise(async(resolve,reject) => {
          try{
            let icGroupItem = new InternetCelebrityGroup()
            let first_name = platformList.find(e => e.ic?.name)
            console.log(first_name,ic_group)
            let ic_group_name = ''
            if(first_name){
              ic_group_name = first_name.ic.name
              //除tk ins，其他平台不可重名
              let level3List = await this.userSettingRespository.query(`select * from setting where setting.key = 'level3'`,[])
              if(!level3List.find(e => e.value.toLocaleLowerCase() == first_name.platform.platform.toLocaleLowerCase())){
                if(ic_group){
                  if(await this.internetCelebrityGroupRespository.findOne({where:{name: ic_group_name, id: Not(ic_group)}})){
                    throw new Error('网红已存在，请更换名字。')
                  }
                }else if(await this.internetCelebrityGroupRespository.findOne({where:{name: ic_group_name}})){
                  throw new Error('网红已存在，请更换名字。')
                }
              }
            }

            if(ic_group){
              await this.internetCelebrityGroupRespository.createQueryBuilder(null, queryRunner)
                .update({name: ic_group_name})
                .where({id: ic_group})
                .execute()
            }else{
              icGroupItem.wx_user = wx_user
              icGroupItem.create_time = new Date()
              icGroupItem.name = ic_group_name
              icGroupItem.id_card = this.getIDCard()
              icGroupItem.type = !isOverseas ? EnumInternetCelebrityGroupTypeEnum.virtual : EnumInternetCelebrityGroupTypeEnum.overseas
              let addIcGroup = await queryRunner.manager.save(icGroupItem)
              if(addIcGroup){
                ic_group = addIcGroup.id
              }
            }
            platformList.map(async (e:{platform:Platform,ic:any}) => {
              let platformItem = new Platform()
              platformItem.platform = e.platform.platform
              platformItem.id = e.platform.id || platformId
              let addPlatform:Platform = new Platform()
              addPlatform.id = platformItem.id
              if(!platformItem.id){
                platformItem.wx_user = wx_user
                platformItem.type = !isOverseas ? TypeEnum.virtual : TypeEnum.overseas
                platformItem.create_time = new Date()
                platformItem.ic_group = ic_group
                addPlatform = await queryRunner.manager.save(platformItem)
              }else{
                await this.respository.createQueryBuilder(null,queryRunner).update({platform: platformItem.platform}).where({id:platformItem.id}).execute()
              }
              //删除图片
              if(e.ic.img_delete){
                //查找原始图片
                let findImg = await this.respository.query(`
                  select * from internet_celebrity where id = ? and img_id != '' and img_id is not null
                `,[e.ic.id])
                if(findImg.length > 0){
                  findImg = findImg[0]
                  await utils.deleteYunRes(findImg.img_id, video_SubAppId_List.answer, true)
                  e.ic.img = ''
                  e.ic.img_id = ''
                }
              }
              //删除头像
              if(e.ic.img_delete_avatar){
                //查找原始图片
                let findImg:InternetCelebrity[] = await this.respository.query(`
                  select * from internet_celebrity where id = ? and avatar_id != '' and avatar_id is not null
                `,[e.ic.id])
                if(findImg.length > 0){
                  await utils.deleteYunRes(findImg[0].avatar_id, video_SubAppId_List.answer, true)
                  e.ic.avatar_id = ''
                  e.ic.avatar_img = ''
                }
              }
              let icItem = new InternetCelebrity()
              icItem.img = e.ic.img
              icItem.img_id = e.ic.img_id
              icItem.name = e.ic.name
              icItem.id = e.ic.id || icId
              icItem.avatar_id = e.ic.avatar_id
              icItem.avatar_img = e.ic.avatar_img
              icItem.account = e.ic.account
              if(!icItem.id){
                icItem.platform = addPlatform.id
                icItem.ic_group = ic_group
                icItem.wx_user = wx_user
                icItem.overseas = !isOverseas ? EnumInternetCelebrityOverseasEnum.virtual : EnumInternetCelebrityOverseasEnum.overseas
                icItem.create_time = new Date()
                //添加网红
                await queryRunner.manager.save(icItem)
              }else{
                await this.icRepository.createQueryBuilder(null,queryRunner).update({
                  account: icItem.account,
                  img: icItem.img,
                  img_id: icItem.img_id,
                  name: icItem.name,
                  avatar_id: icItem.avatar_id,
                  avatar_img: icItem.avatar_img,
                }).where({id:icItem.id}).execute()
              }
              len--
              if(len === 0){
                resolve(true)
              }
            })
          }catch(err){
            reject(err)
          }

        })
      }
      if(len > 0){
        try{
          await run()
        }catch(err){
          // 有错误做出回滚更改
          await queryRunner.rollbackTransaction()
          await queryRunner.release();
          return {error:err}
        }
      }
      await queryRunner.commitTransaction()
      await queryRunner.release();
      return {ic_group:ic_group, error: ''}
    } catch (err) {
      console.log(99999,err,'9999')
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return {error:err}
    }
  }

  /**
   * 添加平台
   * @param platformList
   * @param wx_user
   */
  async addPlatformAnswer(platformList:{platform:Platform,ic:InternetCelebrity}[], wx_user: string, type?: TypeEnum, ic_group?: number, ic_group_type?: EnumInternetCelebrityGroupTypeEnum, addOverseas?: Boolean){
    //查找回答的信息
    let platformId, icId
    //查找网红的平台
    let findPlatform = await this.respository.findOne({where:{wx_user: wx_user, type: TypeEnum.answer}})
    if(findPlatform){
      platformId = findPlatform.id
      //查找网红
      let findIc = await this.icRepository.findOne({where:{wx_user: wx_user, platform: platformId}})
      if(findIc){
        icId = findIc.id
      }
    }
    
    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    try {
      let len = platformList.length
      let platformCount = 1
      for(let i = 0 ; i < platformCount - len; i++){
        let addpf = new Platform()
        let addic = new InternetCelebrity()
        platformList.push({platform:addpf,ic:addic})
      }
      len = platformList.length
      let run = () => {
        return new Promise(async(resolve,reject) => {
          platformList.map(async (e:{platform:Platform,ic:any}) => {
            let platformItem = new Platform()
            platformItem.platform = e.platform.platform
            platformItem.id = e.platform.id || platformId
            let addPlatform:Platform = new Platform()
            addPlatform.id = platformItem.id
            if(!platformItem.id){
              platformItem.wx_user = wx_user
              platformItem.type = TypeEnum.answer
              platformItem.create_time = new Date()
              platformItem.ic_group = ic_group
              addPlatform = await queryRunner.manager.save(platformItem)
            }else{
              await this.respository.createQueryBuilder(null,queryRunner).update({platform: platformItem.platform}).where({id:platformItem.id}).execute()
            }
            //删除图片
            if(e.ic.img_delete){
              //查找原始图片
              let findImg = await this.respository.query(`
                select * from internet_celebrity where id = ? and img_id != '' and img_id is not null
              `,[e.ic.id])
              if(findImg.length > 0){
                findImg = findImg[0]
                await utils.deleteYunRes(findImg.img_id, video_SubAppId_List.answer, true)
                e.ic.img = ''
                e.ic.img_id = ''
              }
            }
            //删除头像
            if(e.ic.img_delete_avatar){
              //查找原始图片
              let findImg:InternetCelebrity[] = await this.respository.query(`
                select * from internet_celebrity where id = ? and avatar_id != '' and avatar_id is not null
              `,[e.ic.id])
              if(findImg.length > 0){
                await utils.deleteYunRes(findImg[0].avatar_id, video_SubAppId_List.answer, true)
                e.ic.avatar_id = ''
                e.ic.avatar_img = ''
              }
            }
            let icItem = new InternetCelebrity()
            icItem.img = e.ic.img
            icItem.img_id = e.ic.img_id
            icItem.name = e.ic.name
            icItem.id = e.ic.id || icId
            icItem.avatar_id = e.ic.avatar_id
            icItem.avatar_img = e.ic.avatar_img
            icItem.account = e.ic.account
            if(!icItem.id){
              icItem.platform = addPlatform.id
              icItem.ic_group = ic_group
              icItem.wx_user = wx_user
              icItem.overseas = EnumInternetCelebrityOverseasEnum.answer
              icItem.create_time = new Date()
              //添加网红
              await queryRunner.manager.save(icItem)
            }else{
              await this.icRepository.createQueryBuilder(null,queryRunner).update({
                account: icItem.account,
                img: icItem.img,
                img_id: icItem.img_id,
                name: icItem.name,
                avatar_id: icItem.avatar_id,
                avatar_img: icItem.avatar_img,
              }).where({id:icItem.id}).execute()
            }
            len--
            if(len === 0){
              resolve(true)
            }
          })
        })
      }
      if(len > 0){
        await run()
      }
      await queryRunner.commitTransaction()
      await queryRunner.release();
      return {ic_group:ic_group}
    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return {error:err}
    }
  }

  /**
   * 添加平台（后台）
   * @param platformList
   * @param wx_user
   */
   async addPlatformBackground(platformList:{platform:Platform,ic:InternetCelebrity}[], wx_user: string, type?: TypeEnum, ic_group?: number, ic_group_type?: EnumInternetCelebrityGroupTypeEnum, addOverseas?: Boolean){
    //查询是否打开了海外素材作者
    let isOverseas = false
    if(addOverseas){
      let findOverseas = await this.userSettingRespository.findOne({where:{key: 'overseas',wx_user: wx_user}})
      if(findOverseas){
        isOverseas = Number(findOverseas.value) == 0 ? false : true
      }
    }
    if(isOverseas){
      ic_group = undefined
    }

    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    try {
      //删除海外素材作者平台信息
      //删除网红组
      await this.internetCelebrityGroupRespository.createQueryBuilder(null,queryRunner).delete().where({wx_user: wx_user, type: EnumInternetCelebrityGroupTypeEnum.overseas}).execute()
      //删除网红
      await this.icRepository.createQueryBuilder(null,queryRunner).delete().where({wx_user: wx_user, overseas: 1}).execute()
      //删除平台
      await this.respository.createQueryBuilder(null,queryRunner).delete().where({wx_user: wx_user, type: 2}).execute()

      let len = platformList.length
      let platformCount = 3
      if(type === TypeEnum.answer){
        platformCount = 1
      }
      for(let i = 0 ; i < platformCount - len; i++){
        let addpf = new Platform()
        let addic = new InternetCelebrity()
        platformList.push({platform:addpf,ic:addic})
      }
      len = platformList.length
      let run = () => {
        return new Promise(async(resolve,reject) => {
          if(type != 1){
            let icGroupItem = new InternetCelebrityGroup()
            icGroupItem.create_time = new Date()
            icGroupItem.wx_user = wx_user
            icGroupItem.id = ic_group
            if(ic_group_type === undefined || isOverseas){
              icGroupItem.type = isOverseas ? EnumInternetCelebrityGroupTypeEnum.overseas : EnumInternetCelebrityGroupTypeEnum.virtual
              let addIcGroup = await queryRunner.manager.save(icGroupItem)
              if(addIcGroup){
                ic_group = addIcGroup.id
              }
            }else{
              icGroupItem.type = ic_group_type
            }
          }
          platformList.map(async (e:{platform:Platform,ic:any}) => {
            let platformItem = new Platform()
            platformItem.platform = e.platform.platform
            platformItem.wx_user = wx_user
            platformItem.id = e.platform.id
            if(type == 1){
              platformItem.type = TypeEnum.answer  
            }else{
              platformItem.type = isOverseas ? TypeEnum.overseas : TypeEnum.virtual
            }
            platformItem.create_time = new Date()
            platformItem.ic_group = ic_group
            //添加平台
            let addPlatform:Platform = await queryRunner.manager.save(platformItem)
            //删除图片
            if(e.ic.img_delete){
              //查找原始图片
              let findImg = await this.respository.query(`
                select * from internet_celebrity where id = ? and img_id != '' and img_id is not null
              `,[e.ic.id])
              if(findImg.length > 0){
                findImg = findImg[0]
                await utils.deleteYunRes(findImg.img_id, video_SubAppId_List.answer, true)
                e.ic.img = ''
                e.ic.img_id = ''
              }
            }
            //删除头像
            if(e.ic.img_delete_avatar){
              //查找原始图片
              let findImg:InternetCelebrity[] = await this.respository.query(`
                select * from internet_celebrity where id = ? and avatar_id != '' and avatar_id is not null
              `,[e.ic.id])
              if(findImg.length > 0){
                await utils.deleteYunRes(findImg[0].avatar_id, video_SubAppId_List.answer, true)
                e.ic.avatar_id = ''
                e.ic.avatar_img = ''
              }
            }

            let icItem = new InternetCelebrity()
            icItem.create_time = new Date()
            icItem.img = e.ic.img
            icItem.img_id = e.ic.img_id
            icItem.name = e.ic.name
            icItem.wx_user = wx_user
            icItem.id = e.ic.id
            icItem.ic_group = ic_group
            icItem.platform = addPlatform.id
            icItem.avatar_id = e.ic.avatar_id
            icItem.avatar_img = e.ic.avatar_img
            icItem.account = e.ic.account
            if(type == 1){
              icItem.overseas = EnumInternetCelebrityOverseasEnum.my
            }else{
              icItem.overseas = isOverseas ? EnumInternetCelebrityOverseasEnum.overseas : EnumInternetCelebrityOverseasEnum.virtual
            }
            //添加网红
            await queryRunner.manager.save(icItem)
            len--
            if(len === 0){
              resolve(true)
            }
          })
        })
      }
      if(len > 0){
        await run()
      }
      await queryRunner.commitTransaction()
      await queryRunner.release();
    } catch (err) {
      console.log(err,'errrr')
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err
    }
  }

  
  /**
   * 添加平台（后台）
   * @param platformList
   * @param wx_user
   */
  async addPlatformBackground_auth(platformList:{platform:Platform,ic:InternetCelebrity}[], wx_user: string, type?: TypeEnum, ic_group?: number, ic_group_type?: EnumInternetCelebrityGroupTypeEnum, addOverseas?: Boolean){
    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    try {
      let len = platformList.length
      let platformCount = 3
      for(let i = 0 ; i < platformCount - len; i++){
        let addpf = new Platform()
        let addic = new InternetCelebrity()
        platformList.push({platform:addpf,ic:addic})
      }
      len = platformList.length
      let run = () => {
        return new Promise(async(resolve,reject) => {
          platformList.map(async (e:{platform:Platform,ic:any}) => {
            let platformItem = new Platform()
            platformItem.platform = e.platform.platform
            platformItem.id = e.platform.id
            platformItem.wx_user = wx_user
            platformItem.create_time = new Date()
            platformItem.ic_group = ic_group
            platformItem.type = TypeEnum.virtual
            let addPlatform:Platform
            if(!platformItem.id){
              addPlatform = await queryRunner.manager.save(platformItem)
            }else{
              await this.respository.createQueryBuilder(null, queryRunner)
                .update({platform: platformItem.platform})
                .where({id: platformItem.id})
                .execute()
              addPlatform = platformItem
            }
            //添加平台
            //删除图片
            if(e.ic.img_delete){
              //查找原始图片
              let findImg = await this.respository.query(`
                select * from internet_celebrity where id = ? and img_id != '' and img_id is not null
              `,[e.ic.id])
              if(findImg.length > 0){
                findImg = findImg[0]
                await utils.deleteYunRes(findImg.img_id, video_SubAppId_List.answer, true)
                e.ic.img = ''
                e.ic.img_id = ''
              }
            }
            //删除头像
            if(e.ic.img_delete_avatar){
              //查找原始图片
              let findImg:InternetCelebrity[] = await this.respository.query(`
                select * from internet_celebrity where id = ? and avatar_id != '' and avatar_id is not null
              `,[e.ic.id])
              if(findImg.length > 0){
                await utils.deleteYunRes(findImg[0].avatar_id, video_SubAppId_List.answer, true)
                e.ic.avatar_id = ''
                e.ic.avatar_img = ''
              }
            }

            let icItem = new InternetCelebrity()
            icItem.create_time = new Date()
            icItem.img = e.ic.img
            icItem.img_id = e.ic.img_id
            icItem.name = e.ic.name
            icItem.wx_user = wx_user
            icItem.id = e.ic.id
            icItem.ic_group = ic_group
            icItem.platform = addPlatform.id
            icItem.avatar_id = e.ic.avatar_id
            icItem.avatar_img = e.ic.avatar_img
            icItem.account = e.ic.account
            if(!icItem.id){
              await queryRunner.manager.save(icItem)
            }else{
              await this.icRepository.createQueryBuilder(null, queryRunner)
                .update({img:icItem.img, img_id: icItem.img_id, name: icItem.name, platform: icItem.platform, avatar_id: icItem.avatar_id, avatar_img: icItem.avatar_img, account: icItem.account,ic_group: icItem.ic_group})
                .where({id: icItem.id})
                .execute()
            }
            len--
            if(len === 0){
              resolve(true)
            }
          })
        })
      }
      if(len > 0){
        await run()
      }
      await queryRunner.commitTransaction()
      await queryRunner.release();

      //删除缓存
      if(ic_group){
        await this.redisCacheService.clear(`icinfo:icgroup:${ic_group}*`)
      }
    } catch (err) {
      console.log(err,'errrr')
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err
    }
  }


  async findAll_By_User(skip: number, take: number,keyword: string, wx_user: string): Promise<{data:Platform[],total:number}> {
    if(skip === -1){
      return {
        data:await this.respository.find({
          where:{wx_user:wx_user},
        }),
        total:0,
      }
    }
    let data = await this.respository.find({
      where:{wx_user:wx_user,platform:Like(`%${keyword}%`)},
      skip:skip,
      take:take
    });
    let total = await this.respository.count({
      where:{wx_user:wx_user,platform:Like(`%${keyword}%`)}
    })
    return {data,total}
  }

  findAll_By_Ic_Group_Virtually(wx_user: string): Promise<Platform[]> {
    return this.respository.query(`
      select a.id as id_platform,a.platform,a.wx_user,b.id as id_ic,b.name as ic_name,b.img,b.img_id,b.avatar_img,b.avatar_id,b.account,a.ic_group from platform a
      inner join internet_celebrity b on b.platform = a.id and b.wx_user = a.wx_user
      left join internet_celebrity_group c on c.id = b.ic_group
      where a.ic_group = ?
      order by a.id asc
    `,[wx_user])
  }

  findAll_By_Wx_User_Overseas(wx_user: string, isOverseas: EnumInternetCelebrityGroupTypeEnum): Promise<Platform[]> {
    return this.respository.query(`
      select a.id as id_platform,a.platform,a.wx_user,b.id as id_ic,b.name as ic_name,b.img,b.img_id,b.avatar_img,b.avatar_id,b.account,a.ic_group from platform a
      inner join internet_celebrity b on b.platform = a.id and b.wx_user = a.wx_user
      left join internet_celebrity_group c on c.id = b.ic_group
      where a.wx_user = ? and c.type = ?
      order by a.id asc
    `,[wx_user, isOverseas])
  }

  async findAll_By_Wx_User(wx_user: string, type?: TypeEnum): Promise<Platform[]> {
    //查找回答的答案（回答问题）
    if(type == 1){
      return await this.respository.query(`
        select a.id as id_platform,a.platform,a.wx_user,b.id as id_ic,b.name as ic_name,b.img,b.img_id,b.avatar_img,b.avatar_id,b.account,a.ic_group from platform a
        inner join internet_celebrity b on b.platform = a.id and b.wx_user = a.wx_user
        left join internet_celebrity_group c on c.id = b.ic_group
        where a.wx_user = ? and a.type = ? and (c.id is null or c.type = 1)
        order by a.id asc
      `,[wx_user, TypeEnum.answer])
    }else{//查找我的答案(认证过)
      //查找审核中的信息
      let findCheckList = await this.internetCelebrityGroupCheckRepository.find({where:{wx_user: wx_user}, order: {'id': 'asc'}})
      let list = []
      if(findCheckList.length > 0){
        findCheckList.map((e: any) => {
          list.push({
            platform:e.platform,
            ic_name: e.name,
            avatar_img: e.avatar_img,
            avatar_id: e.avatar_img_id,
            account: e.account,
            checking: true
          })
        })
      }else{
        list = await this.respository.query(`
          select a.id as id_platform,a.platform,a.wx_user,b.id as id_ic,b.name as ic_name,b.img,b.img_id,b.avatar_img,b.avatar_id,b.account,a.ic_group from platform a
          inner join internet_celebrity b on b.platform = a.id and b.wx_user = a.wx_user and b.ic_group = a.ic_group
          inner join internet_celebrity_group c on c.id = b.ic_group
          where a.wx_user = ? and a.type = ? and (c.id is null or c.type = 2)
          order by a.id asc
        `,[wx_user, TypeEnum.overseas])
      }
      return list
    }
  }

  findOne(id: number): Promise<Platform> {
    return this.respository.findOne({where:{id}});
  }

  async remove(id: number): Promise<void> {
    await this.respository.delete(id);
  }

  async create(data: Platform): Promise<void> {
    await this.respository.save(data);
  }

  async update_background(id:number,platform:string): Promise<void> {
    await this.respository.update({id:id},{platform:platform});
  }
}
